package org.shop.controller.app;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Address;
import org.shop.entity.Favorites;
import org.shop.entity.Goods;
import org.shop.entity.ShoppingTrolley;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.AddressService;
import org.shop.service.FavoritesService;
import org.shop.service.GoodsService;
import org.shop.service.ShoppingCardService;
import org.shop.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ShoppingCardController {
	
	private static Logger logger = LogManager.getLogger(ShoppingCardController.class);
	@Autowired
    private ShoppingCardService shoppingTrolleyService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private FavoritesService favoritesService;
	
	/**
	 * 加入购物车
	 * @param req
	 * @return
	 */
	@RequestMapping("app/addShoppingCard")
	@ResponseBody
	public Map<String, Object> addShoppingCard(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String goodsId = req.getParameter("goodsId");
		String unitPrice = req.getParameter("unitPrice");
		Date orderTime = new Date();
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", ud.getUserId());
			params.put("goodsId", goodsId);
			ShoppingTrolley shoppingTrolley = shoppingTrolleyService.getShoppingCardGoods(params);
			ShoppingTrolley cart = new ShoppingTrolley();
			if(StringUtil.isNullOrEmpty(shoppingTrolley)) {
				cart.setShoppingtrolleyId(shoppingTrolley.getShoppingtrolleyId());
				cart.setUserId(ud.getUserId());
				int orderCount = shoppingTrolley.getOrderCount();
				orderCount += 1;
				cart.setOrderCount(orderCount);
				cart.setGoodsId(Long.parseLong(goodsId));
//				shoppingTrolleyService.updateShoppingCardGoods(params);
				if(unitPrice != null) {
					cart.setOrderPrice(new BigDecimal(unitPrice).multiply(new BigDecimal(orderCount)));
				}
				shoppingTrolleyService.updateByPrimaryKeySelective(cart);
			}else {
				cart.setGoodsId(Long.parseLong(goodsId));
				cart.setUserId(ud.getUserId());
				cart.setUnitPrice(new BigDecimal(unitPrice));
				cart.setOrderCount(1);
				cart.setOrderTime(orderTime);
				cart.setOrderPrice(new BigDecimal(unitPrice));
				shoppingTrolleyService.insertSelective(cart);
			}
			map.put("state", 1);
			map.put("msg", "添加成功");
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "添加失败");
		}
		return map;
	}
	
	/**
	 * 
	 * 获取购物车商品列表
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getShoppingCardList")
//	@ResponseBody
	public String getShoppingCardList(HttpServletRequest req){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		List<ShoppingTrolley> list = shoppingTrolleyService.getShoppingCardList(ud.getUserId());
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", ud.getUserId());
		List<Map<String,Object>> list = shoppingTrolleyService.getShoppingCardList(params);
		req.setAttribute("shoppingList", list);
//		return list;
		return "app/shopping";
	}
	
	/**
	 * 增加我的购物车商品数量
	 * @param req
	 * @return
	 */
	@RequestMapping("app/addShoppingCardCount")
	@ResponseBody
	public Map<String, Object> addShoppingCardCount(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String goodsId = req.getParameter("goodsId");
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			ShoppingTrolley shoppingTrolley = shoppingTrolleyService.selectByPrimaryKey(Long.parseLong(goodsId));
			int goodsCount = shoppingTrolley.getOrderCount();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", ud.getUserId());
			params.put("goodsId", goodsId);
			params.put("goodsCount", goodsCount+1);
			shoppingTrolleyService.updateShoppingCardGoods(params);
			map.put("state", 1);
			map.put("msg", "添加成功");
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "添加失败");
		}
		return map;
	}
	
	/**
	 * 减少我的购物车商品数量
	 * @param req
	 * @return
	 */
	@RequestMapping("app/delShoppingCardCount")
	@ResponseBody
	public Map<String, Object> delShoppingCardCount(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String goodsId = req.getParameter("goodsId");
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			ShoppingTrolley shoppingTrolley = shoppingTrolleyService.selectByPrimaryKey(Long.parseLong(goodsId));
			int goodsCount = shoppingTrolley.getOrderCount()-1;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", ud.getUserId());
			params.put("goodsId", goodsId);
			params.put("goodsCount", goodsCount-1);
			shoppingTrolleyService.updateShoppingCardGoods(params);
			map.put("state", 1);
			map.put("msg", "减少成功");
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "减少失败");
		}
		return map;
	}
	
	/**
	 * 删除我的购物车商品(多选删除)
	 * @param req
	 * @return
	 */
	@RequestMapping("app/delShoppingCard")
	@ResponseBody
	public Map<String, Object> delShoppingCard(HttpServletRequest req){
		String userCheck = req.getParameter("userCheck");
		String goodsIds = req.getParameter("goodsIds");
		
		Map<String, Object> map = new HashMap<String, Object>();
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			
			String[] idArray = goodsIds.split(",");
			for (String id : idArray) {
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("userId", ud.getUserId());
				params.put("userCheck", userCheck);
				params.put("goodsId", id);
                shoppingTrolleyService.delShoppingCardGoods(params);
            }  
			map.put("state", 1);
			map.put("msg", "删除成功");
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "删除失败");
		}
		return map;
	}
	
	/**
	 * 选中（取消选中）购物车商品
	 * @param req
	 * @return
	 */
	@RequestMapping("app/checkShoppingCard")
	@ResponseBody
	public Map<String, Object> checkShoppingCard(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = req.getParameter("goodsIds");
		String userCheck = req.getParameter("userCheck");
		String unitPrice = req.getParameter("unitPrice");
		String orderCount = req.getParameter("orderCount");
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			String[] idArray = ids.split(",");
			for (String id : idArray) {
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("userId", ud.getUserId());
				params.put("goodsId", id);
				params.put("userCheck", userCheck);
				params.put("orderCount", orderCount);
				if(unitPrice != null && orderCount != null) {
					params.put("orderPrice", new BigDecimal(unitPrice).multiply(new BigDecimal(orderCount)));
				}
				shoppingTrolleyService.updateShoppingCardGoods(params);
            }  
			map.put("state", 1);
			map.put("msg", "成功");
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "失败");
		}
		return map;
	}
	
	
	/** 
	* @Title: updAndAddShoppingCard 
	* @Description: TODO(添加或者修改购物车) 
	* @param @param req
	* @param @return     
	* @return int    返回类型 
	* @throws 
	*/
	@RequestMapping("app/updAndAddShoppingCard")
	@ResponseBody
	public int updAndAddShoppingCard(HttpServletRequest req){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String,Object> params = new HashMap<String,Object>();
		int num = 0;
		try{
			Long goodsId = Long.parseLong(req.getParameter("goodsId"));
			int orderCount = Integer.parseInt(req.getParameter("orderCount")); 
			String unitPrice = req.getParameter("unitPrice");
			String orderPrice = req.getParameter("orderPrice");
			String goodsSize = req.getParameter("goodsSize");
			params.put("goodsId", goodsId);
			params.put("userId", ud.getUserId());
			ShoppingTrolley shoppingCard = shoppingTrolleyService.getShoppingCardGoods(params);
			if(shoppingCard!=null){
				shoppingCard.setOrderTime(new Date());
				int a = shoppingCard.getOrderCount()+orderCount;
				shoppingCard.setOrderCount(a);
				shoppingCard.setOrderPrice(new BigDecimal(unitPrice).multiply(new BigDecimal(a)));
				shoppingTrolleyService.updateByPrimaryKeySelective(shoppingCard);
				num = 1;
			}else{
				ShoppingTrolley st = new ShoppingTrolley();
				st.setGoodsId(goodsId);
				st.setOrderCount(orderCount);
				st.setUnitPrice(new BigDecimal(unitPrice));
				st.setOrderPrice(new BigDecimal(orderPrice));
				st.setOrderTime(new Date());
				st.setUserId(ud.getUserId());
				st.setGoodsSize(goodsSize);
				shoppingTrolleyService.insertSelective(st);
				num = 2;
			}
		}catch(Exception e){
			num = 0;
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	
	/**
	 * 获取购物车数量
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getShopCardCount")
	@ResponseBody
	public int getShopCardCount(HttpServletRequest req) {
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		int num = 0;
		try {
			num = shoppingTrolleyService.getMyShoppingCount(ud.getUserId());
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	
	/**
	 * 根据商品ID获取加入购物车商品的数量
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getShopCardGoodsCount")
	@ResponseBody
	public Map<String,Object> getShopCardGoodsCount(HttpServletRequest req) {
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		Map<String,Object> map = new HashMap<String,Object>();
		String goodsId = req.getParameter("goodsId");
		try {
			paramMap.put("goodsId", goodsId);
			paramMap.put("userId", ud.getUserId());
			ShoppingTrolley shoppingCardGoods = shoppingTrolleyService.getShoppingCardGoods(paramMap);
			map.put("shoppingCardGoods", shoppingCardGoods.getOrderCount());
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	/** 
	* @Title: toNowShopping 
	* @Description: TODO(商品详情点击立即购买跳转页面) 
	* @param @param req
	* @param @return     
	* @return String    返回类型 
	* @throws 
	*/
	@RequestMapping("app/toNowShopping")
	public String toNowShopping(HttpServletRequest req){
//		登录信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try{
			Long goodsId = Long.parseLong(req.getParameter("goodsId"));
			int orderCount = Integer.parseInt(req.getParameter("shopcarnum"));
			Goods goods = goodsService.selectByPrimaryKey(goodsId);
			String goodsSize = req.getParameter("goodsSize");//已选择的规格
			//获取默认地址传前台
			Address personDefaultAddress = addressService.getPersonDefaultAddress(ud.getUserId());
			req.setAttribute("goods", goods);
			req.setAttribute("personDefaultAddress", personDefaultAddress);
			req.setAttribute("orderCount", orderCount);
			req.setAttribute("unitPriceTotal", goods.getGoodsPrice().multiply(new BigDecimal(orderCount)));
			req.setAttribute("goodsSize", goodsSize);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/nowShopping";
	}
	
	
	/**
	 * 购物车移入我的收藏
	 * @param req
	 * @return
	 */
	@RequestMapping("app/toMyCollect")
	@ResponseBody
	public int toMyCollect(HttpServletRequest req) {
		int num = 0;
		String ids = req.getParameter("goodsIds");  
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			String[] idArray = ids.split(",");
			for (String id : idArray) {
				Favorites favoritesInfo = new Favorites();
				favoritesInfo.setTargetId(Long.parseLong(id));
				favoritesInfo.setUserId(ud.getUserId());
				Favorites conditions = favoritesService.getFavoritesByTargetIdAndFavoriteType(favoritesInfo);
				if(conditions==null) {
					Favorites favorites = new Favorites();
					favorites.setTargetId(Long.parseLong(id));
					favorites.setUserId(ud.getUserId());
					favoritesService.insertSelective(favorites);
				}else {
					conditions.setCreateDate(new Date());
					favoritesService.updateByPrimaryKeySelective(conditions);
				}
            }  
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", ud.getUserId());
			params.put("userCheck", 1);
            shoppingTrolleyService.delShoppingCardGoods(params);
			num = 1;
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		num = 0;
		}
		return num;
	}
	
	
}
